/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.stv.dpds_klient;

import java.awt.Point;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Martin Strouhal
 */
public class Networker {

    private DatagramSocket socket;
    private LinkedList<Player> players = new LinkedList<>();

    public Networker(Player p) {
        try {
            socket = new DatagramSocket();
        } catch (SocketException ex) {
            Logger.getLogger(Networker.class.getName()).log(Level.SEVERE, null, ex);
        }
        players.add(p);
    }

    public void odesliPaket(DatagramPacket paket) {
        try {
            socket.send(paket);
        } catch (IOException ex) {
            Logger.getLogger(Networker.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    void zpracujPaket(DatagramPacket prijatyPaket) {
        Scanner s = new Scanner(new String(prijatyPaket.getData()));
        s.useDelimiter("-");
        int typZpravy = s.nextInt();
        if (typZpravy == 00) {
            players.add(new Player(s.nextLine(), s.nextInt()));
        } else if (typZpravy == 11) {
           getPlayer(s.nextInt()).zmenPozici(new Point(s.nextInt(), s.nextInt()));
        }
    }
    
    private Player getPlayer(int id){
        for (Player player : players) {
            if(player.getId() == id){
                return player;
            }
        }
        return null;
    }
}
